package com.skytech.component.monitor.enterprise_data_monitoring;


import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.util.ElementAbstractUrl;
import com.skytech.component.monitor.util.FormateConnection;
import com.skytech.component.monitor.util.SaveDataUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static java.lang.Integer.parseInt;

@Service
public class LiaoNingNewService implements CrawlerScript {


    @Autowired
    private SaveDataUtil saveDataUtil;
    private static final Logger log = LoggerFactory.getLogger(LiaoNingNewService.class);
    private static final String province = "辽宁";

    public void start() {
        String url = "http://218.60.25.88/";
        try {
            Document document = FormateConnection.createConnection(Jsoup.connect(url))
                    .get();
            log.info("当前页面--{}", url);
            Elements allElements = document.getAllElements();
            List<String> urlList = ElementAbstractUrl.links(allElements.select("#div1 > table > tbody tr:nth-child(n+2) a"));
            partClickNext(urlList);
        } catch (Exception e) {
            log.error("{}--{}", url, e.getMessage());
        } finally {
            log.info("数据爬取结束");
        }
    }

    private void partClickNext(List<String> urlList) throws IOException {

        for (String url : urlList) {
            //List<String> urlListCity = new ArrayList<>();
            Document document = FormateConnection.createConnection(Jsoup.connect(url))
                    .get();
            log.info("当前页面--{}", url);
            Elements allElements = document.getAllElements();
            Elements elements = allElements.select("body > div.main > div.header > div.content > div > div.mainbar > div > div > ul > li:nth-child(2) > div a");
            for (Element e : elements) {
                String entId = e.attr("href").split("/")[3];
                String entName = e.text().trim();
                String urlHistory = "http://218.60.25.88/Main/History?enterpriseId=" + entId;
                Document documentHistory = FormateConnection.createConnection(Jsoup.connect(urlHistory))
                        .get();
                log.info("当前页面--{}", url);
                //  Elements allElementsNew = documentHistory.getAllElements();
                String page;
                int i = 1;

                String n = documentHistory.getElementsByTag("script").html().split("var")[1].split("\"")[15].trim();
                List<MonitorData> monitorDataList = new ArrayList<>();
                boolean mark = true;
                do {

                    String urlNew = "http://218.60.25.88/main/HistoryAjax?enterpriseId=" + entId + "&pageNum=" + i + "&m=" + n;

                    Document documentNew = FormateConnection.createConnection(Jsoup.connect(urlNew))
                            .get();
                    try {
                        page = documentNew.select("body > div.pager > ul > li:nth-last-child(1) >span >a").attr("href").split("\\(")[1].split("\\)")[0].trim();
                    } catch (Exception ex) {
                        log.error(ex.getMessage());
                        page = "1";
                    }
                    if (parseInt(page) == i) {
                        mark = false;
                    }
                    log.info("当前页面--{}", url);
                    Elements allElementsTmp = documentNew.getAllElements();
                    Elements elementsHistory = allElementsTmp.select("body > div.content_resize.divContainer.dataList > table > tbody > tr:nth-child(n+2)");
                    if (!elementsHistory.text().equals("无查询结果")) {
                        Elements elements2 = elementsHistory.get(0).getElementsByTag("tr");
                        if (!elements2.isEmpty()) {
                            for (Element element : elements2) {
                                MonitorData monitorDataBody = new MonitorData();
                                monitorDataBody.setId(UUID.randomUUID().toString());
                                monitorDataBody.setProvince(province);
                                monitorDataBody.setMonitorType("自动上报监测数据");
                                monitorDataBody.setCompanyName(entName);
                                monitorDataBody.setMonitorPoint(element.getElementsByTag("td").get(0).text());
                                monitorDataBody.setMonitorTime(element.getElementsByTag("td").get(1).text());
                                monitorDataBody.setMonitorInfo(element.getElementsByTag("td").get(2).text());
                                monitorDataBody.setMonitorValue(element.getElementsByTag("td").get(3).text());
                                monitorDataBody.setMonitorStandardValue(element.getElementsByTag("td").get(5).text());
                                monitorDataBody.setOverproof(element.getElementsByTag("td").get(6).text());
                                monitorDataBody.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                                monitorDataList.add(monitorDataBody);
                            }
                        }
                    }
                    i++;
                } while (mark);

                saveDataUtil.saveTag(monitorDataList, province);

            }

        }

    }
}
